package com.mxx.bu_yang.activity.off_line;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mxx.basic.server.RetrofitHelper;
import com.mxx.basic.server.enums.RequestEnum;
import com.mxx.basic.server.retrofit.observer.StringObserver;
import com.mxx.basic.utils.SPUtils;
import com.mxx.basic.utils.ToastUtils;
import com.mxx.bu_yang.R;
import com.mxx.bu_yang.activity.LoginActivity;
import com.mxx.bu_yang.adapter.off_line.FileContentAdapter;
import com.mxx.bu_yang.common.CommonTitleActivity;
import com.mxx.bu_yang.dialog.ModifyBarcodeDialog;
import com.mxx.bu_yang.dialog.TemporaryPositionDialog;
import com.mxx.bu_yang.response.LoginInfoResponse;
import com.mxx.bu_yang.response.TemporaryPositionResponse;
import com.mxx.bu_yang.utils.PermissionUtil;
import com.mxx.common.config.ConstantsConfig;
import com.mxx.common.config.NetUrlConfig;
import com.mxx.common.response.BaseEntityResponse;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: Bu_Yang
 * @Package: com.mxx.bu_yang.activity
 * @ClassName: BarcodeListActivity
 * @Description: java类作用描述
 * @Author: 刘江飞
 * @Version: 1.0
 */
public class FileContentActivity extends CommonTitleActivity implements OnItemChildClickListener {
    private RecyclerView rv_result;
    private TextView tv_submit;

    private FileContentAdapter contentAdapter;
    private final Map<String, Object> map = new HashMap<>();
    private final int SCAN_CODE_OFF_IN = 5;
    private final int SCAN_CODE_OFF_OUT = 6;
    private final int SCAN_CODE_OFF_BACK = 7;
    private final String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    public int getLayoutResId() {
        return R.layout.activity_file_content;
    }

    @Override
    protected int getTitleType() {
        return TITLE_LEFT_BACK_MIDDLE_TITLE_RIGHT_IMAGE;
    }

    @Override
    public void initView() {
        super.initView();
        rv_result = findViewById(R.id.rv_result);
        tv_submit = findViewById(R.id.tv_submit);
        tv_title.setText("文件详情");

        initRvResult();
        initParams();
    }

    private void initRvResult() {
        LinearLayoutManager mManager = new LinearLayoutManager(this);
        mManager.setOrientation(RecyclerView.VERTICAL);
        rv_result.setLayoutManager(mManager);
        if (rv_result.getItemDecorationCount() == 0) {
            RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(@NonNull Rect outRect, @NonNull View view
                        , @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    int mode = parent.getChildLayoutPosition(view);
                    if (mode == 0) {
                        outRect.top = 17;
                        outRect.bottom = 0;
                    } else if (mode == state.getItemCount() - 1) {
                        outRect.top = 0;
                        outRect.bottom = 17;
                    } else {
                        outRect.top = 0;
                        outRect.bottom = 0;
                    }
                }
            };
            rv_result.addItemDecoration(decoration);
        }

        contentAdapter = new FileContentAdapter(R.layout.adapter_barcode_result_new);
        rv_result.setAdapter(contentAdapter);
    }

    private void initParams() {
        int menu_id = (int) getSerValueByKey("menu_id");
        map.put("menu_id", menu_id);
        String file_name = (String) getSerValueByKey("file_name");
        map.put("file_name", file_name);
    }

    @Override
    protected void onStart() {
        super.onStart();
        checkReadAndWritePermission();
    }

    private void checkReadAndWritePermission() {
        PermissionUtil
                .getInstance()
                .requestPermission(this, new PermissionUtil.IPermissionListener() {
                    @Override
                    public void allPermissionGranted() {
                        Log.i("TAG", "");
                        String file_name = (String) map.get("file_name");
                        loadFileContent(file_name);
                    }

                    @Override
                    public void partPermissionRefuse() {
                        Log.i("TAG", "");
                        ToastUtils.showToast(FileContentActivity.this, "权限被拒绝，请手动打开权限");
                    }
                }, permissions);
    }

    private void loadFileContent(String file_name) {
        if (file_name == null || file_name.isEmpty()) {
            ToastUtils.showToast(this, "文件不存在");
            return;
        }
        new Thread(() -> {
            List<String> list = getStrListFromTxtByFileName(file_name);
            runOnUiThread(() -> {
                Log.i("TAG", "");
                contentAdapter.setList(list);
            });

        }).start();

    }

    private List<String> getStrListFromTxtByFileName(String file_name) {
        List<String> list = new ArrayList<>();
        String result = readData(file_name);
        String[] array = result.split(",");
        for (String s:array){
            if (s!=null&&!s.isEmpty()){
                list.add(s);
            }
        }
        return list;
    }

    private String readData(String path) {
        String str = "";
        try {
            FileInputStream fin = new FileInputStream(path);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            str = new String(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return str;
    }

    @Override
    public void initListener() {
        super.initListener();
        tv_submit.setOnClickListener(this);
        contentAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_submit) {
            beforeSubmit();
        }
    }

    private void beforeSubmit() {
        if (contentAdapter == null || contentAdapter.getData().isEmpty()) {
            ToastUtils.showToast(this, "没有需要提交的二维码");
            return;
        }
        int menu_id = (int) map.get("menu_id");
        submit(menu_id);
    }

    //提交
    private void submit(int menu_id) {
        List<String> list = contentAdapter.getData();
        String submit_content = listToString(list);
        if (menu_id != SCAN_CODE_OFF_IN && menu_id != SCAN_CODE_OFF_OUT &&
                menu_id != SCAN_CODE_OFF_BACK) {
            ToastUtils.showToast(this, "目标路径未找到");
            return;
        }
        String requestUrl = getRequestUrl(menu_id);
        if (menu_id == SCAN_CODE_OFF_IN || menu_id == SCAN_CODE_OFF_OUT) {
            Map<String, Object> params = getParams(submit_content);
            String json = new Gson().toJson(params);
            String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
            new RetrofitHelper
                    .Builder()
                    .baseUrl(baseUrl)
                    .appendUrl(requestUrl)
                    .addParams(json)
                    .build()
                    .observable(RequestEnum.METHOD_POST_JSON_STRING)
                    .subscribe(new StringObserver(true, this) {
                        @Override
                        protected void onSuccess(String json) {
                            handleJson(menu_id, json);
                        }

                        @Override
                        protected void onFailed(int code, String msg) {
                            super.onFailed(code, msg);
                            ToastUtils.showToast(FileContentActivity.this, msg);
                        }
                    });
        }
        if (menu_id == SCAN_CODE_OFF_BACK) {
            new RetrofitHelper
                    .Builder()
                    .baseUrl(NetUrlConfig.BASE_URL)
                    .appendUrl(requestUrl)
                    .build()
                    .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                    .subscribe(new StringObserver(true, this) {
                        @Override
                        protected void onSuccess(String json) {
                            List<TemporaryPositionResponse> list = paramsJsonToList(json);
                            showTemporaryPositionDialog(menu_id, submit_content, list);
                        }

                        @Override
                        protected void onFailed(int code, String msg) {
                            super.onFailed(code, msg);
                            ToastUtils.showToast(FileContentActivity.this, msg);
                        }
                    });
        }
    }

    private String listToString(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (String s : list) {
            if (s != null) {
                if (list.indexOf(s) == 0) {
                    result = new StringBuilder(s);
                } else {
                    result.append(",").append(s);
                }
            }
        }
        return result.toString();
    }

    private String getRequestUrl(int menu_id) {
        String url = "";
        if (menu_id == SCAN_CODE_OFF_IN) {
            url = "user/operationReceipt/offlineSubmit";
        }
        if (menu_id == SCAN_CODE_OFF_OUT) {
            url = "user/operationReceipt/offlineOut";
        }
        if (menu_id == SCAN_CODE_OFF_BACK) {
            url = "user/operationReceipt/selTemporary";
        }

        return url;
    }

    private Map<String, Object> getParams(String submit_content) {
        Map<String, Object> map = new HashMap<>();
        map.put("barcode", submit_content);
        LoginInfoResponse response = getLoginInfo();
        if (response != null) {
            int userId = response.userId;
            map.put("userId", userId);
        }
        return map;
    }

    private void handleJson(int menu_id, String json) {
        BaseEntityResponse response = paramsJson(json);
        if (response == null) {
            return;
        }
        String tip = response.tip;
        if (tip == null) {
            return;
        }
        if (menu_id == SCAN_CODE_OFF_IN) {
            tip = "离线入库" + tip;
        }
        if (menu_id == SCAN_CODE_OFF_OUT) {
            tip = "离线出库" + tip;
        }
        if (menu_id == SCAN_CODE_OFF_BACK) {
            tip = "出库货品回退" + tip;
        }

        String finalTip = tip;
        runOnUiThread(() -> {
            ToastUtils.showToast(FileContentActivity.this, finalTip);
            contentAdapter.getData().clear();
            contentAdapter.notifyDataSetChanged();
            setResult(menu_id);
            finish();
        });
    }

    private BaseEntityResponse paramsJson(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        return new Gson().fromJson(json, new TypeToken<BaseEntityResponse>() {
        }.getType());
    }

    private List<TemporaryPositionResponse> paramsJsonToList(String json) {
        BaseEntityResponse response = paramsJson(json);
        if (response == null || response.data == null) {
            ToastUtils.showToast(this, "数据为空");
            return null;
        }
        return new Gson().fromJson(new Gson().toJson(response.data), new TypeToken<List<TemporaryPositionResponse>>() {
        }.getType());
    }

    private void showTemporaryPositionDialog(int menu_id, String barcode, List<TemporaryPositionResponse> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        TemporaryPositionDialog dialog = new TemporaryPositionDialog();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("list", new Gson().toJson(list));
        dialog.setArguments(mBundle);
        dialog.setBackDataListener(response -> {
            String request_url = "user/operationReceipt/deliveryReturn";
            Map<String, String> params = getMapParams(barcode, response);
            goodsBack(menu_id, request_url, params);
        });
        dialog.show(getSupportFragmentManager()
                , "TemporaryPositionDialog");
    }


    private Map<String, String> getMapParams(String barcode, TemporaryPositionResponse response) {
        Map<String, String> map = new HashMap<>();
        if (response == null) {
            ToastUtils.showToast(this, "仓位信息为空");
            return map;
        }
        map.put("barcode", barcode);
        map.put("storId", String.valueOf(response.wareId));
        map.put("storName", response.wareName);
        LoginInfoResponse info = getLoginInfo();
        if (info != null) {
            int userId = info.userId;
            map.put("userId", String.valueOf(userId));
        }

        return map;
    }


    private void goodsBack(int menu_id, String request_url, Map<String, String> query) {
        String json = new Gson().toJson(query);
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL)
                .appendUrl(request_url)
                .addParams(json)
                .build()
                .observable(RequestEnum.METHOD_POST_JSON_STRING)
                .subscribe(new StringObserver(true, this) {
                    @Override
                    protected void onSuccess(String json) {
                        handleJson(menu_id, json);
                    }
                });
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (view.getId() == R.id.tv_result) {
            showModifyDialog(position);
        }
    }

    private void showModifyDialog(int position) {
        String barcode = contentAdapter.getItem(position);
        ModifyBarcodeDialog dialog = new ModifyBarcodeDialog();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("barcode", barcode);
        dialog.setArguments(mBundle);
        dialog.setDialogResultListener(result -> runOnUiThread(() -> {
            List<String> list = new ArrayList<>();
            list.add(result);
            contentAdapter.getData().remove(position);
            list.addAll(contentAdapter.getData());
            contentAdapter.setList(list);
            autoInputmethod(FileContentActivity.this);
        }));
        dialog.show(getSupportFragmentManager(), "ModifyBarcodeDialog");
    }

    /**
     * 根据输入法的状态显示和隐藏输入法
     */
    public static void autoInputmethod(Context context) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(INPUT_METHOD_SERVICE);
        assert imm != null;
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    }
}
